<!-- Commentcomponent.vue -->
<template>
  <!-- 遮罩层 -->
  <div class="mask" :class="{ 'show': modelValue }" @click="changeShow"></div>

  <!-- 评论弹窗 -->
  <div class="commit_list" :class="{ 'show': modelValue }">
    <div class="commit_list_top">
      <span class="commit_list_top__num">{{ commentList.length }}条评论</span>
      <span class="commit_list_top__close" @click="changeShow">
        <Icon name="close" size="18" color="#505052" />
      </span>
    </div>

    <div class="commit_list_wrap">
      <!-- 评论列表 -->
      <div class="commit_list_wrap_item" v-for="item in commentList" :key="item.Comment.commentId">
        <!-- 头像 -->
        <div class="commit_list_wrap_item__avatar">
          <img :src="'http://43.138.15.137:3000' + item.Comment.userAvatar" alt="">
        </div>
        <!-- 内容 -->
        <div class="commit_list_wrap_item_main">
          <div class="name">@{{ item.Comment.userNickname }}</div>
          <div class="content">{{ item.Comment.commentContent }}</div>
          <!-- 使用格式化后的时间 -->
          <div class="time">{{ formatTime(item.Comment.createdAt).formatted }}</div>
        </div>

        <!-- 点赞 -->
        <div class="commit_list_wrap_item_like" @click="likeComment(item.Comment.commentId)">
          <Icon name="xin-2" size="18" :color="item.Comment.isLiked ? '#FF4D4F' : '#ccc'" />
          <span class="like-desc">{{ item.likeNum }}</span>
        </div>
      </div>

      <div class="commit_list_wrap_more">查看更多评论</div>
    </div>

    <!-- 输入框 -->
    <div class="input_bar">
      <input type="text" ref="InputFocus" placeholder="有爱评论，说点儿好听的~（长按评论回复）" v-model="inputValue">
      <div class="input_bar_icon" @click="getMentionFriendList">
        <Icon name="aite" size="18" color="#fff" />
      </div>
      <div class="input_bar_icon" @click="publishComment()">
        <Icon name="dui" size="18" color="#fff" />
      </div>
    </div>
  </div>
  <!-- @好友组件 -->
  <!-- 过渡 从下到上 -->
  <transition name="fade">
    <MentionFriendComponent v-if="isShowMentionFriendComponent" v-model="isShowMentionFriendComponent"
      @postselectUser="postselectUser" :mentionFriendList="mentionFriendList" />
  </transition>
</template>

<script setup>
import Icon from '@/components/Common/Icon/index.vue'
import { ref, watch } from 'vue'
import { publishCommentAPI, mentionFriendListAPI, publishCommentAtUserAPI } from '@/api/Home'
import { commentLikeAPI } from '@/api/follow'
import { useUserIDStore } from '@/stores/UserID'

// 🔥 引入时间格式化组合式函数
import { useDateFormat } from '@/composables/useDateFormat'

const inputValue = ref('')

const props = defineProps({
  modelValue: Boolean,
  commentList: {
    type: Array,
    default: () => []
  },
  videoId: {
    type: [Number, String],
    default: '' // 推荐设为必传
  }
})

const InputFocus = ref(null)
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    InputFocus.value.focus()
  }
})

const emit = defineEmits(['update:modelValue', 'newComment'])

// ✅ 创建一个工具函数：返回格式化对象 { formatted }
const formatTime = (timestamp) => {
  return useDateFormat(timestamp, 'YYYY-MM-DD', { relative: true })
}

// 发布评论
const publishComment = async () => {
  const content = inputValue.value.trim()
  if (!content) return

  try {
    const userIDStore = useUserIDStore()
    const userId = userIDStore.userInfo?.userId
    const videoId = props.videoId

    if (!userId || !videoId) {
      console.error('用户ID或视频ID缺失')
      return
    }

    // 1. 先发布主评论
    const res = await publishCommentAPI({
      content,
      fromUserId: userId,
      toVideoId: videoId,
      replyId: ''
    })

    if (res.code !== 200) {
      console.error('发布失败:', res.msg)
      return
    }

    const { commentId, createdAt, commentContent } = res.data

    // 2. 如果内容包含 @，再额外调用 @ 接口（不影响主评论发布）
    if (content.includes('@') && friendId.value) {
      try {
        await publishCommentAtUserAPI(userId, {
          commentId,
          userIdStr: friendId.value,
          videoId: props.commentList[0].Comment.videoId
        })
        console.log('成功@用户')
      } catch (atError) {
        console.warn('发布@关系失败，但评论已成功:', atError)
        // 可选：这里可以提示“评论成功，但@通知未送达”等
      }
    }

    // 3. 无论如何，只要主评论成功，就 emit 给父组件
    emit('newComment', {
      Comment: {
        commentContent,
        commentId,
        commentReplyID: '',
        createdAt,
        userAvatar: userIDStore.userInfo.userAvatar || '',
        userId,
        userNickname: userIDStore.userInfo.userNickname || '',
        videoId
      },
      likeNum: '0',
    })

    inputValue.value = ''
    friendId.value = '' // 清空已选好友 ID

  } catch (error) {
    console.error('发布评论失败:', error)
  }
}

// 关闭弹窗
const changeShow = () => {
  emit('update:modelValue', false)
}

// 评论点赞
const likeComment = async (commentId) => {
  const userIDStore = useUserIDStore();
  const userId = userIDStore.userInfo?.userId;

  try {
    const res = await commentLikeAPI(userId, props.videoId, commentId);

    if (res.code === 200) {
      // 查找对应的评论项
      console.log(props.commentList)
      const targetComment = props.commentList.find(item => item.Comment.commentId === commentId);

      if (targetComment) {
        if (res.data === '喜欢评论成功') {
          // 如果点赞成功，改变点赞状态和增加点赞数
          targetComment.Comment.isLiked = true;
          targetComment.likeNum++;
        } else if (res.data === '取消喜欢评论成功') {
          // 如果取消点赞成功，改变点赞状态和减少点赞数
          targetComment.Comment.isLiked = false;
          targetComment.likeNum--;
        }
      }
    } else {
      console.error('点赞失败:', res.msg);
    }
  } catch (error) {
    console.error('点赞评论失败:', error);
  }
}

import { defineAsyncComponent } from 'vue'
// @好友组件
const isShowMentionFriendComponent = ref(false)
const MentionFriendComponent = defineAsyncComponent(() => import('@/views/home/Commentcomponent/MentionFriendComponent/index.vue'))



// 获取@好友列表
const mentionFriendList = ref([])
const getMentionFriendList = async () => {
  const userIDStore = useUserIDStore();
  const userId = userIDStore.userInfo?.userId;
  try {
    const res = await mentionFriendListAPI(userId);
    if (res.code === 200) {
      isShowMentionFriendComponent.value = true
      // 处理好友列表数据
      console.log('@好友列表:', res.data);
      // 对数据进行二次处理 userAvatar 拼接 http://43.138.15.137:3000
      res.data.forEach(item => {
        item.userAvatar = item.userAvatar ? `http://43.138.15.137:3000${item.userAvatar}` : ''
      })
      mentionFriendList.value = res.data || []
      // 可以将好友列表数据赋值给组件的状态变量，用于渲染
    } else {
      console.error('获取@好友列表失败:', res.msg);
    }
  } catch (error) {
    console.error('获取@好友列表失败:', error);
  }
}
// 接受@好友组件传递过来的用户昵称
// 接受传递过来的 userId
const friendId = ref('')
const postselectUser = (user) => {
  friendId.value = user.userId
  inputValue.value += '@' + user.userNickname
}
</script>

<style lang="scss" scoped>
.mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 254;
  display: none;

  &.show {
    display: block;
  }
}

.commit_list {
  position: fixed;
  bottom: 0;
  height: 70%;
  width: 100%;
  background: rgba(22, 24, 35, 0.98);
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  z-index: 255;
  transition: all 0.3s ease-in-out;
  transform: translateY(100%);

  &.show {
    transform: translateY(0);
  }


  .commit_list_top {
    height: 40px;
    position: relative;
    text-align: center;
    color: #626260;
    font-size: 12px;
    font-weight: bold;
    border-bottom: 1px solid rgba(41, 40, 37, 0.8);
    background: rgba(22, 24, 35, 0.98);

    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 222;

    .commit_list_top__close {
      position: absolute;
      right: 18px;
      top: 50%;
      transform: translateY(-50%);
    }
  }

  .commit_list_wrap {
    position: absolute;
    top: 32px;
    bottom: 44px;
    overflow: hidden;
    width: 100%;
    // y 轴方向滚动
    overflow-y: auto;
    // 添加属性 不影响其他元素的滚动
    scrollbar-width: none;

    &::-webkit-scrollbar {
      width: 0;
      height: 0;
    }

    .commit_list_wrap_item {
      display: flex;
      padding: 0 0 0 10px;
      display: -webkit-box;

      .commit_list_wrap_item__avatar {
        width: 40px;
        height: 40px;

        img {
          width: 100%;
          height: 100%;
          margin-top: 10px;
          border-radius: 50%;
        }
      }

      .commit_list_wrap_item_main {
        padding: 10px;
        -webkit-box-flex: 1;
        -ms-flex: 1;
        flex: 1;
        border-bottom: 1px solid rgba(41, 40, 37, 0.8);
        color: #a6a5a4;
        font-size: 12px;

        .content {
          padding: 5px 0;
          color: #e8e8e9;
          font-size: 14px;
        }
      }

      .commit_list_wrap_item_like {
        width: 44px;
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        -webkit-box-orient: vertical;
        -webkit-box-direction: normal;
        -ms-flex-direction: column;
        flex-direction: column;
        -webkit-box-pack: center;
        -ms-flex-pack: center;
        justify-content: center;
        -webkit-box-align: center;
        -ms-flex-align: center;
        align-items: center;
        color: #505052;

        .like-desc {
          font-size: 12px;
        }
      }


    }

    .commit_list_wrap_more {
      text-align: center;
      font-size: 12px;
      color: #65676e;
      padding-bottom: 12px;
      margin: 14px 0;
    }
  }

  .input_bar {
    width: 100%;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    height: 44px;
    position: absolute;
    bottom: 0;
    background: #1a1b20;

    input {
      background: #1a1b20;
      -webkit-box-flex: 1;
      -ms-flex: 1;
      flex: 1;
      font-size: 14px;
      color: #e8e8e9;
      padding-left: 10px;
      caret-color: #face15;
    }

    .input_bar_icon {
      width: 44px;
      height: 44px;
      display: flex;
      justify-content: center;
      align-items: center;

    }
  }
}

// 过渡 从下到上
.fade-enter-active,
.fade-leave-active {
  transition: all 0.3s ease-in-out;
}

.fade-enter-from,
.fade-leave-to {
  transform: translateY(100%);
}
</style>